//
//  GnetQM_Server_CSCCheckVER.m
//  GnetCommonFrame
//
//  Created by Gnet on 15/6/8.
//  Copyright (c) 2015年 Ymac. All rights reserved.

#import "GnetQM_Server_CSCCheckVER.h"

@interface GnetQM_Server_CSCCheckVER () <NSURLSessionDataDelegate>
@property (nonatomic,copy)  NSString    *verUrl;
@property (nonatomic,copy)  NSString    *tSoapString;
@property (nonatomic,strong)NSData      *receivedData;
@property (nonatomic,strong)NSURLSession*theConnection;
@property (nonatomic,copy)  GnetQM_Server_CSCCheckVERCallBack cvCallBack;

- (void)startRequest;

@end



@implementation GnetQM_Server_CSCCheckVER

- (instancetype)init {
    if (self = [super init]) {
        self.HTTP =Define_Default_HTTP;
        self.PLATFORMTYPE =Define_Default_PLATFORMTYPE;
		self.APPUNIQUEID = Define_Default_APPUNIQUEID;
		self.CURRENTVER = Define_Default_CURRENTVER;
    }
    return self;
}

+ (instancetype)shareSingleton {
	static id instance;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		instance = [[self alloc]init];
	});
	
	return instance;
}

-(NSURLSession *)theConnection {
	if (_theConnection == nil) {
		_theConnection = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
	}
	return _theConnection;
}

-(NSString *)tSoapString {
	if (nil == _tSoapString) {
		_tSoapString = [NSString stringWithFormat:@"{\"GII_HEAD\": {\"VERSION\": \"PC2.0\",\"SNID\": \"20140113140645068\",\"SIGN\": [{\"position/k\": \"\"}, {\"RandomCode/v\": \"\"}],\"GZIP\": \"true\",\"CLOUDID\": \"\"},\"GII_IBD\": {\"REQUEST\": {\"USEID\": \"\",\"APPID\": \"\",\"USERTYPE_ID\": \"%@\",\"SETUP_NAME\": \"%@\"}}}",
                        
                        self.PLATFORMTYPE,
                        self.APPUNIQUEID];

	}
	return _tSoapString;
}

- (void)startCSCCheckVERCallBack:(GnetQM_Server_CSCCheckVERCallBack)callBack {
    if (callBack) {
        _cvCallBack =callBack;
        [self startRequest];
    }
}

- (void)startRequest {
	NSString    *tUrl =[NSString stringWithFormat:@"%@/Gnet_Ibd_Iom/services/Ibd_CommonRest/GII_APP_GetAppByCloudIdAndAppIdOrUseId",
						self.HTTP];
	NSData      *JsonData =[self.tSoapString dataUsingEncoding:NSUTF8StringEncoding];
	
	NSLog(@"检查版本更新");
//	NSLog(@"检查版本Url: =%@", tUrl);
//	NSLog(@"检查版本Msg: =%@", self.tSoapString);
	
	NSMutableURLRequest* tUrlRequest =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:tUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:6];
	[tUrlRequest setHTTPMethod:@"POST"];
	[tUrlRequest addValue:@"http://webService.gnet.cn.com" forHTTPHeaderField:@"action"];
	
    if (self.theConnection) {
        [[self.theConnection uploadTaskWithRequest:tUrlRequest fromData:JsonData completionHandler:^(NSData * data, NSURLResponse * response, NSError * error) {
			if (!error) {
				self.receivedData = data;
				[self finishRequest];
			} else {
				_cvCallBack(nil, nil, nil, -2);
			}
		}]resume];
    }
}

// 接收完数据
- (void)finishRequest {
	NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.receivedData options:NSJSONReadingMutableLeaves error:nil];
//    NSLog(@"检查版本Resp: %@", [dict description]);
	
	NSDictionary *GII_HEADDict = [dict objectForKey:@"GII_HEAD"];

	if ([[GII_HEADDict objectForKey:@"RESCODE"] isEqualToString:@"0000"]) {
		//有数据,RESCODE为"0000"
		NSDictionary *GII_IBDDict = [dict objectForKey:@"GII_IBD"];
		//判断@"MaxVersionUseId"是否为数组,否则不进行解析
		if ([[GII_IBDDict objectForKey:@"MaxVersionUseId"] isKindOfClass:[NSArray class]]) {
            /**
             *  APP_ID              app数据库id
             *  APP_REMARK          app的简介
             *  INSTALL_ADDRESS     app下载安装路径
             *  SETUP_NAME          app唯一包名/build identity
             *  TEMPLATE_TYPE
             *  UPDATE_DETAILS
             *  UPDATE_REMARK       app新版本更新内容提示
             *  USE_ID
             *  VERSION             app新版本号
             *  VERSION_SORT
             */
            
			NSDictionary *MaxVersionUseIdDict = [[GII_IBDDict objectForKey:@"MaxVersionUseId"] lastObject];
			NSString *appURL        =[MaxVersionUseIdDict objectForKey:@"INSTALL_ADDRESS"];
			NSString *appVersion    =[MaxVersionUseIdDict objectForKey:@"VERSION"];
            NSString *tVerMsg       =[MaxVersionUseIdDict objectForKey:@"UPDATE_REMARK"];
            
            NSComparisonResult tCompareResult =[appVersion compare:self.CURRENTVER options:NSNumericSearch];
            if (tCompareResult==NSOrderedAscending){
                _cvCallBack(appURL, appVersion, tVerMsg, -1);   //本地版本较高
            } else if (tCompareResult==NSOrderedDescending){
                _cvCallBack(appURL, appVersion, tVerMsg, 1);    //新版本较高
            } else {
                _cvCallBack(appURL, appVersion, tVerMsg, 0);    //相同
            }
		} else {
			NSLog(@"\"MaxVersionUseId\"不是一个数组,解析失败");
            _cvCallBack(nil, nil, nil, -2);
		}
	} else {
		//若为空,RESCODE不为"0000"
		NSLog(@"版本检测请求内容有误,没有返回值");
        _cvCallBack(nil, nil, [GII_HEADDict objectForKey:@"MSG"], -2);
	}
}

@end